package cn.zk.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * ClassName: CuratorFour
 * Desc: Master选举
 * Date： 2016/12/7
 * Created：shaom
 */
public class CuratorFour {

    static String master_path = "/curator_mater_path";//选举根节点
    public static final String connectString = "master:2181,slave01:2181,slave02:2181";

    // 客户端
    static CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectString)
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(5000, 3))
            .build();


    public static void main(String[] args) throws InterruptedException {
        client.start();

        // 选举类
        // Curator 会在成功获取Master权利的时候回调该监听器
        LeaderSelector selector = new LeaderSelector(client, master_path, new LeaderSelectorListenerAdapter() {

            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                System.out.println("成为Master角色");
                Thread.sleep(3000);//业务逻辑
                System.out.println("完成Master 选举操作，释放Master 权利");
            }
        });

        selector.autoRequeue();
        selector.start();
        Thread.sleep(Integer.MAX_VALUE);
    }

}
